package com.citytransport.prokopjuk.servlets;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;

import com.citytransport.prokopjuk.route.Route;
import com.citytransport.prokopjuk.route.Station;
import com.citytransport.prokopjuk.vehicleDTO.Vehicle;
import com.citytransport.prokopjuk.builder_strategy.Director;
import com.citytransport.prokopjuk.builder_strategy.SimpleRouteBuilder;
import com.citytransport.prokopjuk.dao.DAORoute;
import com.citytransport.prokopjuk.dao.DAOStation;

public class RouteListServlet extends AbstractCommand {
   
    private static final long serialVersionUID = -7362982323045743725L;
    static Logger logger = Logger.getLogger(RouteListServlet.class.getName());
    private DAORoute daoRoute = new DAORoute();
    private DAOStation daoStation = new DAOStation();
    private Director director = new Director();
    private SimpleRouteBuilder builder;

    @Override
    public void processRequest(HttpServletRequest req, HttpServletResponse resp) {
	List<Route> routes = new ArrayList<Route>();
	if (req.getParameter("allRoute") != null) {
	    String vehicleType = req.getParameter("allRoute");
	    routes = new ArrayList<Route>(daoRoute.readCertainRoute(vehicleType));
	 } else {
	    if (req.getParameter("routeID") != ""){
		int routeID = Integer.parseInt(req.getParameter("routeID"));
		Route tmp = daoRoute.read(routeID);
		int price = tmp.getPrice();
		int intervalMinute = tmp.getIntervalMinute();
		ArrayList<Station> stations = new ArrayList<Station>(daoStation.readAtRoute(routeID));
		builder = new SimpleRouteBuilder(daoRoute.readVehicle(routeID), stations, price, intervalMinute, routeID);
		director.setRouteBuilder(builder);
		director.createRoute();
		routes.add(director.getRoute());
	    }else{
		  try {
		    req.getRequestDispatcher("/BadRequest.jsp").forward(req, resp);
		} catch (ServletException e) {
		   logger.error(e);
		 } catch (IOException e) {
		    logger.error(e);
		}
	    }
	}
	try {
	    req.setAttribute("routes", routes);
	    req.getRequestDispatcher("/routeList.jsp").forward(req, resp);
	} catch (ServletException e) {
	   logger.error(e);
	} catch (IOException e) {
	    logger.error(e);
	}
    }
}
